package com.hardydou.framework.auth;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.hardydou.common.utils.RegionUtil;
import com.hardydou.system.model.LoginUserDetails;
import com.hardydou.system.model.SystemLoginLog;
import com.hardydou.system.model.SystemUser;
import com.hardydou.system.service.ISystemLoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：hardy
 * @description：登录验证成功
 * @date ：Created in 2020/6/4
 * @Copyright ：Hardydou.com
 */
public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ISystemLoginLogService loginLogService;

    /**
     * Called when a user has been successfully authenticated.
     *
     * @param request        the request which caused the successful authentication
     * @param response       the response
     * @param authentication the <tt>Authentication</tt> object which was created during
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        super.onAuthenticationSuccess(request, response, authentication);
        SystemUser loginUser = ((LoginUserDetails) authentication.getPrincipal()).getSystemUser();
        UserAgent ua = UserAgentUtil.parse(request.getHeader("User-Agent"));
        SystemLoginLog loginLog = new SystemLoginLog();
        String ip = ServletUtil.getClientIP(request);
        loginLog.setLoginIp(ip);
        loginLog.setLoginBrowser(ua.getBrowser().toString());
        loginLog.setUserName(loginUser.getUsername());
        loginLog.setUserId(loginUser.getUserId());
        loginLog.setLoginLocation(RegionUtil.getRegion(ip));
        loginLog.setLoginOs(ua.getOs().toString());
        loginLog.setFail(false);
        loginLog.setRemark("");
        loginLogService.add(loginLog);

    }
}
